//
//  KCLabel.m
//  ReplyAssistant
//
//  Created by Leo on 2018/12/1.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KCLabel.h"

@implementation KCLabel

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        _padding = UIEdgeInsetsZero;
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    _padding = UIEdgeInsetsZero;
}

- (void)drawTextInRect:(CGRect)rect {
    
//
//
//    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.padding)];
}

- (CGSize)intrinsicContentSize {
    CGSize size = [super intrinsicContentSize];
    CGFloat width = size.width + 10;
    CGFloat height = size.height;
    return CGSizeMake(width, height);
}


- (void)setAllowCopy:(BOOL)allowCopy {
    
    if (_allowCopy != allowCopy) {
        _allowCopy = allowCopy;
    }
    
    if (_allowCopy) {
        self.userInteractionEnabled = YES;
        self.longTaper = [[UILongPressGestureRecognizer alloc] initWithTarget: self action: @selector(on_longTap:)];
        [self addGestureRecognizer: self.longTaper];
    }
    else {
        [self removeGestureRecognizer: self.longTaper];
    }
}

- (void)on_longTap:(UILongPressGestureRecognizer*)per {
    
    UIGestureRecognizerState state = per.state;
    //     防止长按之后连续触发该事件
    if (state == UIGestureRecognizerStateBegan) {
        // UILabel成为第一响应者
        [self becomeFirstResponder];
        
        UIMenuController *menuVC = [UIMenuController sharedMenuController];
        [menuVC setTargetRect:self.frame inView:self.superview];
        [menuVC setMenuVisible:YES animated:YES];
    }
}

- (BOOL)canBecomeFirstResponder {
    return true;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copy:)) {
        return YES;
    }
    return NO;
}

- (void)copy:(id)sender {
    [UIPasteboard generalPasteboard].string = self.text;
}

@end
